#!/bin/bash

# 下载配置文件地址
resource_raw_url="https://gitee.com/magein/shell-utils/raw/master/resources"

# 配置文件列表
config=("conf.json" "script.json" "dockerfile.json")

# 需要使用到的命令
commands=("jq")
# 需要安装的命令
install_commands=()

# 公共函数
common='/root/common'
wget "$resource_raw_url/common" -O "$common" >/dev/null 2>&1
echo "Common file download completed"
# 引入公共函数
source "/root/common"

# 下载配置文件
downloadConfig() {

  echo "Start download config from:$resource_raw_url"

  for item in "${config[@]}"; do

    save_path="/root/.${item}"
    # 下载config.json文件
    if [ -f "$save_path" ]; then
      rm -rf "$save_path"
    fi

    wget "$resource_raw_url/${item}" -O "$save_path" >/dev/null 2>&1
    if [ -f "$save_path" ]; then
      echo " ${item} download completed"
    fi

  done
}

downloadScript() {

  # 远程脚本文件地址
  script_json="/root/.script.json"
  script_raw_url=$(getConfig "script.raw" "$script_json")

  if [ ${#script_raw_url} -eq 0 ]; then
    printError "script.json文件中script.raw parameter empty"
  fi

  # 脚本文件列表
  files=$(getConfig "script.list" "$script_json")

  # 获取脚本的保存位置
  local_storage=$(getConfig "local.storage.script" "$script_json")

  # 批量下载远程文件
  downloadRemoteFiles "$local_storage" "$script_raw_url" "$files"
}

init() {
  # 检查需要使用的命令是否存在
  for item in "${commands[@]}"; do
    which "${item}" >/dev/null 2>&1
    if [ "$?" -eq 1 ]; then
      install_commands+=("${item}")
    fi
  done

  if [ "${#install_commands}" -gt 0 ]; then

    format "error:" "Please use the following command to install"

    for item in "${install_commands[@]}"; do
      commands=("apt-get" "yum" "dnf")
      for command in "${commands[@]}"; do
        which "$command" >/dev/null 2>&1
        if [ "$?" -eq 0 ]; then
          echo "  $command -y install ${item}"
        fi
      done
    done

    exit
  fi

  #
  # 下载配置文件
  #
  downloadConfig

  #
  # 下载脚本文件
  #
  downloadScript
}

eval set -- "$(getopt -q -o "hp:o" -l help,path:,os -- "$@")"

while [ -n "$1" ]; do
  case $1 in
  -h | --help)
    echo ""
    echo "Usage:"
    usageFormat "-h,--help:" "Get help documents"
    usageFormat "-p,--path:" "Set the shell script save path,default ${base}"
    echo ""
    echo "Description:"
    echo "   Please execute this file as root"
    exit
    ;;
  -p | --path)
    base="$2"
    shift 2
    ;;
  *)
    break
    ;;
  esac
done

init
